"use strict"
//个人订单
const P = require('bluebird')
const moment = require('moment')
const mvc = require("cosjs.mvc");
exports.page = function () {
    let sid = this.get('sid', 'int')
    let $page = this.get('page', 'int') || 1;
    let $size = this.get('size', 'int') || 20;
    let body = this.req.body;
    let format = mvc.format("orderOne");
    let q = this.library.call(this, 'jqgrid/query', body, format) || {}
    let orderModel = mvc.model.mongo('order', sid)
    let roleModel = mvc.model.mongo('role', sid)
    let query = {}
    let dbsort = {
        time: -1
    };
    let option = {
        projection: ['uid', 'val', 'time', 'status', 'zb', 'zbMax', 'gc', 'gcMax']
    }
    return Promise.resolve().then(() => {
        if (q.name) {
            return roleModel.find(q, {
                projection: ['_id', 'guid']
            })
        }
        return 'yyb'
    }).then(role => {
        if (role) {
            if (role !== 'yyb') {
                //单查
                query.uid = role._id
            }
            return orderModel.page(query, $page, $size, dbsort, option).then(ret => {
                if (role && role !== 'yyb') {
                    return [role, ret];
                } else {
                    return P.map(ret.rows, i => roleModel.find({
                        _id: i.uid
                    }, {
                        projection: ['name', 'guid']
                    })).then(docs => [docs, ret])
                }
            }).then(result => {
                let role = result[0]
                let ret = result[1]
                ret.rows.forEach((v, k) => {
                    if (q.name) {
                        v.name = q.name
                        v.guid = role.guid
                    } else {
                        v.name = role[k] ? role[k].name : ""
                        v.guid = role[k] ? role[k].guid : ""
                    }
                    v.time = moment(new Date(v.time)).format('YYYY-MM-DD HH:mm')
                })
                return ret;
            })
        } else {
            return { "rows": [] };
            //查无此人
        }
    })
}